<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Category;
use App\Tools\HgTool;
use Input,DB;

class CategoryController extends Controller
{
    public function index(Request $request,$id=0){
    	$cat = new Category;

    	//判断是文章类目还是书籍
    	switch($id){
    		case 0:
	    		$catData = $cat->leftJoin('category as c1','category.pid','=','c1.id')->select('category.*','c1.name as pname')->where('category.is_type',0)->paginate(10);
	    		break;
    		case 1:
    			$catData = $cat->where('is_type',1)->paginate(10);
    			break;
    	}

    	$data['categoryCount'] = $cat->count();
    	$data['catData'] = $catData;

    	return view('admin.cat_list',$data);

    	
    }


    public function add(Request $request,$id=0){
    	$cat = new Category;
    	
    	//判断是文章类目还是书籍
    	switch($id){
    		case 0:
	    		$catData = $cat->where('is_type',0)->get();
	    		break;
    		case 1:
    			$catData = $cat->where('is_type',1)->get();
    			break;
    	}

    	// 递归无限级分类
    	$tool = new HgTool;
    	$data['catData'] = $tool->getTree($catData);

    	if($request->isMethod('post')){
    		$arr = Input::only('name','pid','sex');
    		$cat->insert($arr);
    	}

    	return view('admin.cat_add',$data);
    }


    public function edit(Request $request,$id){
    	$cat = new Category;
    	$data['catInfo'] = $cat->find($id);

    	//判断是文章类目还是书籍
    	switch($id){
    		case 0:
	    		$catData = $cat->where('is_type',0)->paginate(10);
	    		break;
    		case 1:
    			$catData = $cat->where('is_type',1)->paginate(10);
    			break;
    	}

    	$data['catData'] = $catData;

    	if($request->isMethod('post')){
    		$arr = Input::only('name','pid','sex');
    		$cat->where('id',$id)->update($arr);
    		return redirect('/Admin/Category/list');
    	}

    	return view('admin.cat_edit',$data);

    }



    public function del(Request $request,$id){
    	$cat = new Category;
    	$cat->where('id',$id)->delete();
    	return redirect('/Admin/Category/list');
    }

}
